#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from marshmallow import ValidationError

from app.utils.responses import api_response, api_error_response
from ...services.user_service import UserService
from app.api.schemas.user_schema import UserSchema, UserCreateSchema, UserUpdateSchema
from app.api.controllers.user_controller import (
    get_users, 
    get_user_by_id, 
    create_user, 
    update_user, 
    delete_user
)

# 创建用户蓝图
user_bp = Blueprint('user', __name__, url_prefix='/api/users')

# 实例化验证模式
user_schema = UserSchema()
users_schema = UserSchema(many=True)
user_create_schema = UserCreateSchema()
user_update_schema = UserUpdateSchema()

# 实例化用户服务
user_service = UserService()

@user_bp.route('', methods=['POST'])
def list_users():
    """获取用户列表 - 使用POST而非传统GET"""
    # 从JSON请求体中获取分页参数等
    data = request.get_json() or {}
    page = data.get('page', 1)
    per_page = data.get('per_page', 10)
    
    users = get_users(page, per_page)
    return api_response(users_schema.dump(users))

@user_bp.route('/detail', methods=['POST'])
def get_user():
    """获取单个用户详情 - 使用POST请求"""
    data = request.get_json() or {}
    user_id = data.get('id')
    
    if not user_id:
        return api_error_response("用户ID不能为空", 400)
    
    user = get_user_by_id(user_id)
    if not user:
        return api_error_response("用户不存在", 404)
    
    return api_response(user_schema.dump(user))

@user_bp.route('/create', methods=['POST'])
def add_user():
    """创建新用户"""
    data = request.get_json() or {}
    
    try:
        # 验证请求数据
        user_data = user_create_schema.load(data)
    except ValidationError as e:
        return api_error_response(f"数据验证错误: {str(e)}", 422)
    
    # 创建用户
    user = create_user(user_data)
    return api_response(user_schema.dump(user), "用户创建成功", 201)

@user_bp.route('/update', methods=['POST'])
@jwt_required
def modify_user():
    """更新用户信息"""
    data = request.get_json() or {}
    user_id = data.get('id')
    
    if not user_id:
        return api_error_response("用户ID不能为空", 400)
    
    try:
        # 验证请求数据
        user_data = user_update_schema.load(data)
    except ValidationError as e:
        return api_error_response(f"数据验证错误: {str(e)}", 422)
    
    # 更新用户
    user = update_user(user_id, user_data)
    if not user:
        return api_error_response("用户不存在", 404)
    
    return api_response(user_schema.dump(user), "用户更新成功")

@user_bp.route('/delete', methods=['POST'])
@jwt_required
def remove_user():
    """删除用户"""
    data = request.get_json() or {}
    user_id = data.get('id')
    
    if not user_id:
        return api_error_response("用户ID不能为空", 400)
    
    # 删除用户
    success = delete_user(user_id)
    if not success:
        return api_error_response("用户不存在或删除失败", 404)
    
    return api_response(None, "用户删除成功")

@user_bp.route('/profile', methods=['POST'])
@jwt_required()
def get_profile():
    """获取当前用户信息
    
    使用POST+JSON形式请求，返回当前登录用户的信息
    """
    # 获取当前用户ID
    current_user_id = get_jwt_identity()
    
    # 获取用户信息
    user = user_service.get_user_by_id(current_user_id)
    
    if not user:
        return api_error_response("用户不存在", 404)
    
    return api_response(user_schema.dump(user), "获取个人信息成功")


@user_bp.route('/update', methods=['POST'])
@jwt_required()
def update_profile():
    """更新当前用户信息
    
    使用POST+JSON形式请求，更新当前登录用户的信息
    """
    # 验证请求数据必须是JSON
    if not request.is_json:
        return api_error_response("请求必须是JSON格式", 400)
    
    # 获取当前用户ID
    current_user_id = get_jwt_identity()
    
    # 加载并验证数据
    try:
        data = user_update_schema.load(request.json)
    except Exception as e:
        return api_error_response(f"数据验证失败: {str(e)}", 400)
    
    # 更新用户信息
    result = user_service.update_user(current_user_id, data)
    
    if not result['success']:
        return api_error_response(result['message'], 400)
    
    return api_response(result['user'], "更新个人信息成功") 